﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlCommandHelper;
using System.Data;

namespace Vergnaty.Repository
{
    public class GenericTableRepository
    {

        string _connectionString;
        public GenericTableRepository(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString", "cannot be null or empty");

            _connectionString = connectionString;
        }

        /// <summary>
        /// Get all datas of TEntity
        /// </summary>
        /// <typeparam name="TEntity">TEntity</typeparam>
        /// <returns>List of TEntity</returns>
        public IList<TEntity> GetDatas<TEntity>()
            where TEntity : class
        {
            List<TEntity> entities;
            using (SqlConnection connection = new SqlConnection(_connectionString))
            {
                connection.Open();
                Type type = typeof(TEntity);

                //Get attibute value
                string tableName = type.GetAttributeValue((DbTable t) => t.Name);
                string schema = type.GetAttributeValue((DbTable t) => t.Schema);

                //if you want to use storedprocedure use EXEC(SELECT *FROM ......)
                string commandText = string.Format("SELECT *FROM [{0}].[{1}]",schema,tableName);
                
                //set sql command
                SqlCommand command = new SqlCommand();
                command.Connection = connection;
                command.CommandText = commandText;
                command.CommandType = CommandType.Text;
              
                //execute reader
                using (IDataReader reader = command.ExecuteReader())
                {
                    entities = reader.MapToEntityList<TEntity>().ToList();
                }
            }
            return entities;
        }
    }
}
